# -*- coding:utf-8 -*-

"""
    激活zip包，使其处于可更新状态
"""

import tornado.web
from service import base
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config



@route('/manage/status/?', 'manage.status')
class ActivateHandler(base.BaseWebHandler):
    """ 设置zip包状态
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        status = self.get_argument('status', None)
        _id = self.get_argument('_id', None)

        results = {
                   'code':          0,
                   'info':          'set status success!',
                   '_id':           _id,
                   'status':        status
                   }

        if status not in ['0', '1'] or not _id:
            results['code'] = 1
            results['info'] = 'params error!'
            self.finish(results)
            return

        spec = {'_id': _id}
        r = yield tornado.gen.Task(mongo.find_one, self.db_name, self.collection_name, spec)
        if not r:
            logger.debug('could not find datas, results =', results, caller=self)
            results['code'] = 1
            results['info'] = 'could not find!'
            self.finish(results)
            return

        fields = {'status': status}
        r = yield tornado.gen.Task(mongo.update, self.db_name, self.collection_name, spec, fields)
        if not r:
            logger.error('update error! results =', results, caller=self)
            results['code'] = 2
            results['info'] = 'update failed!'
            self.finish(results)
            return

        self.finish(results)
        logger.info('update success! results =', results, caller=self)

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self, *argl, **argd):
        self.get(*argl, **argd)

